package com.xiaochong.bitong.api.service;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.reflect.TypeToken;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.bitong.api.constant.ReturnCode;
import com.xiaochong.bitong.api.userclient.JsonView;
import com.xiaochong.bitong.api.userclient.UserServiceClient;
import com.xiaochong.bitong.api.utils.ListSortUtil;
import com.xiaochong.service.common.config.oss.OSSTool;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.common.data.mapper.AboutMapper;
import com.xiaochong.tir.common.data.mapper.BtUserInfoMapper;
import com.xiaochong.tir.common.data.mapper.BtUserMapper;
import com.xiaochong.tir.common.data.mapper.CCountryNumMapper;
import com.xiaochong.tir.common.data.po.About;
import com.xiaochong.tir.common.data.po.BtUserInfo;
import com.xiaochong.tir.common.data.po.CCountryNum;
import com.xiaochong.tir.common.data.vo.BtUser;
import com.xiaochong.tir.common.data.vo.CountrysData;
import com.xiaochong.tir.common.data.vo.app.UserVo;
import com.xiaochong.tir.common.util.RedisKeyApp;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Project : xc-tir
 * @Package Name : com.xiaochong.bitong.api.service
 * @Description : TODO
 * @Author : daizhiqing@xiaochong.com
 * @Creation Date : 2018年08月10日下午4:24
 * @ModificationHistory Who When What
 */
@Service
public class UserService {

    @Autowired
    private BtUserInfoMapper btUserInfoMapper;

    @Autowired
    private BtUserMapper btUserMapper;

    @Autowired
    private OSSTool ossTool;

    @Autowired
    private RedisServer redisServer;

    @Autowired
    private CCountryNumMapper cCountryNumMapper;


    @Autowired
    private UserServiceClient userServiceClient;

    @Autowired
    CommonService commonService;

    @Autowired
    AboutMapper aboutMapper;


    /**
     *  获取手机国别号列表
     * @return
     */
    public List<CountrysData> getCountryNums(){

        List<CountrysData> countryNumsList = new ArrayList<>(  );
        if(redisServer.exists(RedisKeyApp.COUNTRY_NUM)){
            countryNumsList = redisServer.getList(RedisKeyApp.COUNTRY_NUM , new TypeToken< List<CountrysData>>(){}.getType());
        }else{
            CCountryNum cCountryNum = new CCountryNum();
            cCountryNum.setHot( 1 );
            List<CCountryNum> countryNums = cCountryNumMapper.getAllCountryNums( cCountryNum );
            String[] letterList = new String[]{"A","B","C","D","E","F","G","H","I","G","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};

            for(int k=0;k<letterList.length;k++){
                CountrysData countrysData = new CountrysData();
                List<CCountryNum> countrys = new ArrayList<>(  );
                for(int i=0;i<countryNums.size();i++){
                    CCountryNum countryNum = countryNums.get( i );
                    if(countryNum.getSpellInitial().equals( letterList[k] )){
                        countrys.add( countryNum );
                        countrysData.setCountrys( countrys );
                        countrysData.setSpellInitial( countryNum.getSpellInitial());
                    }
                }
                countryNumsList.add( countrysData );
            }

            if(countryNumsList != null && countryNumsList.size() >0 ){
                LogTrace.info("getCountryNums"  , "size" ,countryNumsList.size()+"");
                redisServer.set(RedisKeyApp.COUNTRY_NUM , countryNumsList ,RedisKeyApp.ExpireTime.ONE_DAY );
            }

        }

        return countryNumsList;
    }


    /**
     * 发送短信验证码
     * @param countryNum
     * @param account
     * @param type
     * @param params
     * @return
     */
    public JsonView sendSmsCode(String countryNum,
                           String account,
                            Integer type,
                            String params){
        LogTrace.infoKvs("获取验证码", "account",account , "type",type+"" , "params",params);
        String result=userServiceClient.sendValidCode( countryNum,account,ReturnCode.PLATFORM,type,params  );
        LogTrace.info("发送验证码结果", "result",result );

        if(StringUtils.isNotBlank(result)){
            JsonView object  = JSONObject.parseObject(result , JsonView.class);
            return object;
        }
        return  null;
    }

    /**
     * 注销用户登录
     * @param userToken
     */
    public void logoutUserToken(String userToken){
        LogTrace.info("注销登录", "开始执行注销登录接口",userToken);
        String result=userServiceClient.logoutUserToken(userToken);
        redisServer.remove(RedisKeyApp.USER_TOKEN+userToken);
    }


    /**
     * 插入用户对象
     * @param userVo
     * @return
     */
    public BtUser insertUserVo(UserVo userVo){

        BtUser btUser = new BtUser();
        btUser.setMobile(userVo.getMobile());
        btUser.setEmail(userVo.getEmail());
        btUser.setCountryNum(userVo.getCountryNum());
        btUser.setCreateTime(userVo.getCreateTime());
        btUser.setSource(userVo.getPlatform()+"");
        if(btUserMapper.insert(btUser) >0){

            BtUserInfo btUserInfo=new BtUserInfo();
            String userName = "bitong"+btUser.getId();
            btUserInfo.setUserName(userName);
            btUserInfo.setUserId( btUser.getId() );
            btUserInfoMapper.insertSelective( btUserInfo );

            btUser.setUserName(userName);
            return btUser;
        }
        return null;
    }


    /**
     * 验证码登录
     * @param countryNum
     * @param phone
     * @param code
     * @param codeToken
     * @return
     */
    public JsonView smsCodeLogin(String countryNum,
                             String phone,
                             String code,
                             String codeToken){
        LogTrace.infoKvs("短信验证码登录", "phone",phone ,"code" ,code,"codeToken",codeToken);

        String result=userServiceClient.validCodeLogin(countryNum,phone,code,codeToken,ReturnCode.PLATFORM);
        LogTrace.infoKvs("验证码登录结果", "result",result );

        JsonView jsonView = null;
        if(StringUtils.isNotBlank(result)){
            jsonView = JSONObject.parseObject(result , JsonView.class);
            if(ReturnCode.SUCCESS.endsWith(jsonView.getCode())){
                LogTrace.infoKvs("短信验证成功", "phone",phone ,"code" ,code,"codeToken",codeToken);

                UserVo userVo =  JSONObject.parseObject(jsonView.getData().toString() , UserVo.class);
                String  userKey = RedisKeyApp.USER_TOKEN+userVo.getToken();
                BtUser btUser = new BtUser();
                btUser.setEmail( userVo.getEmail() );
                btUser.setMobile( userVo.getMobile() );
                List<BtUser> btList = btUserMapper.selectByAccount( btUser );
                if(btList != null && btList.size()>0){
                    btUser = btList.get(0);
                    LogTrace.infoKvs("平台老用户", "btUser",btUser.toString());
                }else{
                    btUser = insertUserVo(userVo);
                    LogTrace.infoKvs("平台新用户", "btUser",btUser.toString());
                }
                if(StringUtils.isNotBlank(btUser.getImageUrl())){
                    String imgUrl=ossTool.getOSSUrl( btUser.getImageUrl() );
                    btUser.setImageUrl(imgUrl);
                }
                redisServer.set(userKey , btUser ,RedisKeyApp.ExpireTime.ONE_DAY*7);
            }
        }

        return jsonView;
    }

    /**
     * 设置昵称
     * @param token
     * @param userName
     * @return
     */
    public boolean setUserName(String token  , String userName){
        BtUser btUser = commonService.getUserByToken(token);

        if(btUser == null){
            return false;
        }
        int userId =  btUser.getId();
        LogTrace.infoKvs("修改昵称" , "userID" ,userId+"" , "userName",userName);
        BtUserInfo btUserInfo=new BtUserInfo();
        btUserInfo.setUserName(userName);
        BtUserInfo useNameUse = btUserInfoMapper.selectByEntity(btUserInfo);
        if(useNameUse == null){
            BtUserInfo btUserInfoUser =  btUserInfoMapper.selectByPrimaryKey(userId);
            if(btUserInfoUser != null){
                btUserInfoUser.setUserName(userName);
                btUserInfoMapper.updateByPrimaryKey(btUserInfoUser);
                LogTrace.infoKvs("修改昵称成功" , "userID" ,userId+"" , "userName",userName);
                btUser.setUserName(userName);
                commonService.refreshUserToken(token , btUser);
                return true;
            }
            LogTrace.infoKvs("用户信息不存在" , "userID" ,userId+"" , "userName",userName);
        }
        LogTrace.infoKvs("修改昵称已存在" , "userID" ,userId+"" , "userName",userName);
        return false;
    }


    /**
     * 查询币通官方社群1 或者  2为关于币通
     * @param type
     * @return
     */
    public List<About>  getAppAboutList(String type){

        if(StringUtils.isNotBlank(type)){
            About about = new About();
            about.setType(type);
            List<About> aboutList = aboutMapper.selectByEntityList(about);
            return aboutList;
        }
        return null;
    }
}
